package sfin.controller;

import sfin.service.CategoriaService;
import sfin.swt.exception.StatizoException;
import br.com.statizo.financeiro.domain.entity.impl.Categoria;
import br.com.statizo.financeiro.domain.enums.GrupoLancamento;

public class CategoriaController {

	private CategoriaService service;
	private int selectedIndex = -1;
	
	private String descricao = "";
	private int grupoIndex = -1;
	
	public CategoriaController(CategoriaService service) {
		this.service = service;
	}
	
	public String[][] getCategorias(){
		return service.getCategorias();
	}
	
	public void setSelectedIndex(int selectedIndex) {
		this.selectedIndex = selectedIndex;
		loadData();
	}
	
	private void loadData() {
		if(selectedIndex >= 0){
			Categoria categ = service.getAt(selectedIndex);
			descricao = categ.getNome();
			grupoIndex = categ.getGrupo().ordinal();
			selectedIndex = service.indexOf(categ);
		}else{
			clearSelection();
		}
	}

	public int getSelectedIndex() {
		return selectedIndex;
	}
	
	public String getDescricao() {
		return descricao;
	}
	
	public void setDescricao(String descricao) {
		this.descricao = descricao;
	}
	
	public int getGrupoIndex() {
		return grupoIndex;
	}
	
	public void setGrupoIndex(int grupoIndex) {
		this.grupoIndex = grupoIndex;
	}
	
	public String[] getGrupos(){
		GrupoLancamento[] grupos = GrupoLancamento.values();
		String[] names = new String[grupos.length];
		for (int i = 0; i < grupos.length; i++) {
			names[i] = grupos[i].getNome();
		}
		return names;
	}

	public void callSave() throws StatizoException{
		this.selectedIndex = service.add(selectedIndex,descricao, grupoIndex);
		loadData();
	}

	public void callDel() throws StatizoException{
		service.del(selectedIndex);
	}

	public void clearSelection() { 
		this.descricao = "";
		this.grupoIndex = -1;
		this.selectedIndex = -1;
	}

	public boolean existeCategoria() {
		return service.count() > 0;
	}
}
